<?php
/**
 * Created by Yevgen Vershynin.
 * User: Yevgen Vershynin
 * Description: Main entry point for application
 */

error_reporting(E_ALL);
ini_set('display_errors', '1');

//Autoload rules
spl_autoload_register('apiAutoload');
function apiAutoload($classname)
{
    //Rule for all Controllers
    if (preg_match('/[a-zA-Z]+Controller$/', $classname))
    {
        include __DIR__ . '/controllers/' . $classname . '.php';
        return true;
    }
    //Rule for all Models
    elseif (preg_match('/[a-zA-Z]+Model$/', $classname))
    {
        include __DIR__ . '/models/' . $classname . '.php';
        return true;
    }
    //Rule for all Views
    elseif (preg_match('/[a-zA-Z]+View$/', $classname))
    {
        include __DIR__ . '/views/' . $classname . '.php';
        return true;
    }
    //Rule for all Components
    elseif (preg_match('/[a-zA-Z]+Component$/', $classname))
    {
        include __DIR__ . '/components/' . $classname . '.php';
        return true;
    }
    //Rule for all Objects
    elseif (preg_match('/[a-zA-Z]+Object$/', $classname))
    {
        include __DIR__ . '/models/objects/' . $classname . '.php';
        return true;
    }
}

//Create request object
$request = new RequestComponent();
//Route the request to the right place
$controllerName = ucfirst($request->urlElements[1]) . 'Controller';
if (class_exists($controllerName))
{
    //Init correct controller
    $controller = new $controllerName();
    $actionName = strtolower($request->verb) . 'Action';
    //Call action according to request.
    $result = $controller->$actionName($request);

    $viewName = ucfirst($request->format) . 'View';
    if(class_exists($viewName))
    {
        $view = new $viewName();
        //Render result for the client.
        $view->render($result);
    }
}